﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Lead2012.Business;

namespace Lead2012.Repository
{
    public class FieldItemManagementRepository
    {
        // Create an instance of entity
        Lead2012Entities entities = new Lead2012Entities();

        public List<FieldItemInfo> GetAllItemByField(int id)
        {
            var items= (from c in entities.FieldItems
                    where c.FieldId == id
                    orderby c.OrderId ascending
                    select c).ToList();

            List<FieldItemInfo> list = new List<FieldItemInfo>();

            foreach (var item in items)
            {
                FieldItemInfo model = new FieldItemInfo();
                model.Id = item.ItemId;
                model.OrderId = item.OrderId;
                model.Title = item.Title;
                list.Add(model);
            }

            return list;
        }

        public FieldItem GetSingle(int id)
        {
            return (from _object in entities.FieldItems where _object.ItemId == id select _object).FirstOrDefault();
        }

        public void Create([Bind(Exclude = "ID")] FieldItem _object, int fieldId)
        {
            _object.FieldCustomReference.EntityKey = new EntityKey("LeadCRMEntities.FieldCustoms", "FieldId", fieldId);
            entities.AddToFieldItems(_object);
            entities.SaveChanges();
        }

        public void Create([Bind(Exclude = "ID")] FieldItem _object)
        {
            entities.AddToFieldItems(_object);
            entities.SaveChanges();
        }
        public void Update(FieldItem _object)
        {
            entities.SaveChanges();
        }

        public void Delete(int id)
        {
            var _object = (from _list in entities.FieldItems where _list.ItemId == id select _list).First();
            entities.DeleteObject(_object);
            entities.SaveChanges();
        }
    }
}